package com.wuxiaolong.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuxiaolong.wechat.common.BusinessException;
import com.wuxiaolong.wechat.common.ResultCode;
import com.wuxiaolong.wechat.model.AccessToken;
import com.wuxiaolong.wechat.service.AccessTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * Description:
 *
 * @author Leo
 * @date 2020-02-13
 */
@Slf4j
@Service
public class AccessTokenServiceImpl implements AccessTokenService {

    @Value("${wechat.appID}")
    private String appID;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Value("${wechat.tokenUrl}")
    private String tokenUrl;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 存储token的对象,用于外部调用
     */
    private AccessToken at;


    @Override
    public String getAccessToken(){
        if(at !=null && at.getExpires_time() > System.currentTimeMillis()){
            return at.getAccess_token();
        }else {
            return getWeChatToken();
        }
    }

    private String getWeChatToken(){
        String tempUrl = tokenUrl.replace("APPID",appID).replaceAll("APPSECRET",appSecret);
        log.info("获取Token请求参数：{}", tempUrl);
        AccessToken resp = restTemplate.getForObject(tempUrl, AccessToken.class);
        log.info("获取Token响应参数：{}", JSON.toJSONString(resp));

        if(resp != null  && ! StringUtils.isEmpty(resp.getAccess_token())){

            // 设置过期时间
            resp.setExpires_time(System.currentTimeMillis() + resp.getExpires_in()*1000);
            // 存储token
            this.at = resp;
            log.info("存储的token:{}", JSON.toJSONString(at));
            return resp.getAccess_token();
        }
        log.error("access_token获取失败。");
        throw new BusinessException(ResultCode.ACCESS_TOKEN_ERR.getCode(),ResultCode.ACCESS_TOKEN_ERR.getMsg());

    }
}
